IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[cms_sp_EntityMetaSelectFor]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[cms_sp_EntityMetaSelectFor]
GO
create procedure [dbo].[cms_sp_EntityMetaSelectFor]
@EntityId int = null,
@EntityTypeParameter nvarchar(255)
as
select 
	EntityMetaFields.EntityMetaFieldId,
	MetaFieldName,
	MetaFieldDescription,
	MetaFieldType,
	IsSystem
from [dbo].[EntityMetaFields]
inner join [dbo].[EntityMetaFieldLinks]
	on EntityMetaFields.EntityMetaFieldId = EntityMetaFieldLinks.EntityMetaFieldId
where EntityMetaFieldLinks.EntityTypeParameter = @EntityTypeParameter
order by EntityMetaFieldLinks.MetaFieldOrder
select
	EntityMetaFieldLinkId,
	EntityMetaFieldId,
	EntityTypeParameter,
	DisplayLabel,
	IsAllowMultipleValues,
	MetaFieldValues,
	IsRequired,
	MetaFieldOrder,
	DefaultValue,
	EditorName
from [dbo].[EntityMetaFieldLinks]
where EntityMetaFieldLinks.EntityTypeParameter = @EntityTypeParameter
order by EntityMetaFieldLinks.MetaFieldOrder
select 
	EntityMetas.EntityMetaId,
	EntityMetas.EntityMetaFieldLinkId,
	EntityMetas.EntityId,
	EntityMetas.EntityMetaValue
from [dbo].[EntityMetas]
inner join [dbo].[EntityMetaFieldLinks]
	on EntityMetas.EntityMetaFieldLinkId = EntityMetaFieldLinks.EntityMetaFieldLinkId
	and EntityMetaFieldLinks.EntityTypeParameter = @EntityTypeParameter
where (((EntityMetas.EntityId = @EntityId) and @EntityId is not null) or (@EntityId is null))
order by EntityMetaFieldLinks.MetaFieldOrder


GO

